//
//  JiZhenDetailViewController.m
//  安好
//
//  Created by rlp on 14-12-9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "JiZhenDetailViewController.h"
// 区分模拟器和真机
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR 1
#elif TARGET_OS_IPHONE
#define SIMULATOR 0
#endif
@interface JiZhenDetailViewController ()

@end

@implementation JiZhenDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    if (!self.symptomEmeDetailBaseClass) {
        self.symptomEmeDetailBaseClass = [[SymptomEmeDetailBaseClass alloc]init];
    }
    
    [self makeNavBarView];
    [self makeTableView];
    [self loadEmeDetail];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - 设置导航条
-(void)makeNavBarView
{
      self.title = self.emeName;
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // “筛选”
    UIButton *rightButtonMore = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButtonMore.frame = CGRectMake(0,0, 23, 23);
    [rightButtonMore setImage:[UIImage imageNamed:@"公用_更多"] forState:UIControlStateNormal];
    [rightButtonMore addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:rightButtonMore];
    
    
}

-(void)leftButtonClicked:(UIButton *)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)rightButtonClicked:(UIButton *)sender{
    NSString *collectionStr =nil;
   if ([[NSString stringWithFormat:@"%.f",self.symptomEmeDetailBaseClass.data.iscollection] isEqualToString:@"1"]) {
        collectionStr = @"取消收藏";
   }else{
       collectionStr = @"收藏";

   }
    
    
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    NSArray *images = @[@"百科_收藏", @"帖子底部_未分享"];
    NSArray *selectImages = @[@"百科_收藏成功", @"帖子底部_已分享"];
    NSArray *titles = @[collectionStr, @"分享"];

    PopoverView *pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectImages];
    pop.selectRowAtIndex = ^(NSInteger index){
        MyNSLog("select index:%d", index);
        switch (index) {
            case 0:
            {
                [self isLogin];


            }
                break;
            case 1:
            {
                [self showShareView];
            }
                break;
                
            default:
                break;
        }
    };
    [pop show];

    
}
/**
 *  添加收藏
 */

-(void)addOrDeleteCollectionUrlStr:(NSString *)urlStr{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    
    [dict setObject:@"8" forKey:@"type"];//类型 1：疾病2：医院3：科室4：医生5；药品6新闻:7:话题8：急诊9:常识
    if ([urlStr isEqualToString:COLLECTION_DELETE]) {
        //删除收藏
    }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
        //添加收藏
        [dict setObject:[NSString stringWithFormat:@"%@",self.emeName] forKey:@"title"];
        
        
    }
    
    [dict setObject:[NSString stringWithFormat:@"%.f",self.symptomEmeDetailBaseClass.data.emeid] forKey:@"objectid"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,urlStr] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            }else{
                if ([urlStr isEqualToString:COLLECTION_DELETE]) {
                    //删除收藏
                    
                    [self showCustomHudSingleLine:@"取消收藏失败"];
                }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
                    [self showCustomHudSingleLine:@"添加收藏失败"];

                }
            }
            
        }else{
            
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            }else{
                if ([urlStr isEqualToString:COLLECTION_DELETE]) {
                    //删除收藏
                    
                    [self showCustomHudSingleLine:@"取消收藏成功"];
                }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
                    [self showCustomHudSingleLine:@"添加收藏成功"];
                    
                }
            }
            if ([urlStr isEqualToString:COLLECTION_DELETE]) {
                //删除收藏

                self.symptomEmeDetailBaseClass.data.iscollection =0;
            }else if ([urlStr isEqualToString:COLLECTION_ADDCOLLECTION]) {
                //添加收藏

                self.symptomEmeDetailBaseClass.data.iscollection =1;
                
            }
            
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:@"请检查网络"];
        
    }];
    
}

#pragma mark - 创建tableView 设置table的代理、添加头视图横线
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
    //    //创建头视图 - 一条线
    //    self.headerLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    //    self.headerLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    //    self.tableView.tableHeaderView = self.headerLineView;
}

#pragma mark - 加载疾病的详细信息
-(void)loadEmeDetail
{
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:self.emeId forKey:@"emeid"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,SYMOPTOM_EMEDETAIL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
        MyNSLog("%@",responseObject);
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];//失败
        }else{
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                self.symptomEmeDetailBaseClass = [SymptomEmeDetailBaseClass modelObjectWithDictionary:responseObject];
                
                
                self.picurl = [[NSString alloc] initWithString:self.symptomEmeDetailBaseClass.data.picurl];
                [NSThread detachNewThreadSelector:@selector(downloadPic) toTarget:self withObject:nil];
                self.dataArray = [[NSMutableArray alloc] initWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"more"]];
                
                for(int i=0; i<[self.dataArray count]; i++)
                {
                    //保存cell的高度和btn的title，cell的高度默认是105
                    NSDictionary *subDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"108", @"cellHeight", @"阅读全部", @"btnTitle", nil];
                    [self.allCellInfo addObject:subDic];
                }
                [self.tableView reloadData];
            }else{
                [self showCustomHudSingleLine:@"网络数据格式错误"];
            }
            
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];
 }
//在线程里下载图片，根据图片的只存判断第一行的高度
-(void)downloadPic
{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.picurl]]]];
    imageView.contentMode = UIViewContentModeTop;
    
    //计算图片的高度
    self.firstRowHeight = imageView.frame.size.height * 260 / imageView.frame.size.width;
    [self.tableView reloadData];
}
#pragma mark - tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0)
    {
        if(self.firstRowHeight == 0)
            return 480.0f;
        return self.firstRowHeight + 40;
    }
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [self.dataArray count] + 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //第一个cell是现实判断流程的，有图片和别的不能复用
    if(indexPath.row == 0)
    {
        static NSString *identifer = @"identifer";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 18.0f, kScreenWidth-15*2, 14)];
            titleLabel.text = [NSString stringWithFormat:@"%@判断流程", self.emeName];
            titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
            titleLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];
            [cell.contentView addSubview:titleLabel];
        }
        
        
        //流程图
        self.contentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 38, kScreenWidth-40, self.firstRowHeight)];
        [self.contentImageView setImageWithURL:[NSURL URLWithString:self.picurl] placeholderImage:nil];
        self.contentImageView.contentMode = UIViewContentModeScaleAspectFit;
        
        //流程图添加单击手势
        UITapGestureRecognizer *tapImageView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPic:)];
        [self.contentImageView addGestureRecognizer:tapImageView];
        self.contentImageView.userInteractionEnabled = YES;
        [cell.contentView addSubview:self.contentImageView];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else
    {
        static NSString *cellIdentifer = @"cellIdentifer";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        }
        
        //titleLabel
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 9, kScreenWidth-15*2, 0) text:[[self.dataArray objectAtIndex:indexPath.row - 1] objectForKey:@"title"] font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE] textColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] backgroundColor:[UIColor clearColor] numberOfLines:0 lineSpacing:5];

        [cell.contentView addSubview:titleLabel];
        
        //contentLabel
        UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, titleLabel.frame.size.height+titleLabel.frame.origin.y+5, kScreenWidth-15*2, 0) text:TextString([[self.dataArray objectAtIndex:indexPath.row - 1] objectForKey:@"content"]) font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13] textColor:TITLE_ARTICLE_CONTENTFONT_COLOR backgroundColor:[UIColor clearColor]
             numberOfLines:0 lineSpacing:5];

        [cell.contentView addSubview:contentLabel];
        
        cell.frame = CGRectMake(0, 0, kScreenWidth, contentLabel.frame.size.height+contentLabel.frame.origin.y+10);
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}
-(void)showPic:(UITapGestureRecognizer*)tap{
    
   UIImageView *viewImage = (UIImageView*)tap.view;
    
    
    
    NSMutableArray *arrimages = [[NSMutableArray alloc ]initWithObjects:self.picurl, nil];
        NSInteger count = arrimages.count;
    
        // 1.封装图片数据
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            // 替换为中等尺寸图片
//            NSString *url = arrimages[i];
            MJPhoto *photo = [[MJPhoto alloc] init];
            NSString *url =nil;
            NSRange range;
            range = [arrimages[i] rangeOfString:@"@"];
            if (range.location != NSNotFound) {
                url = [arrimages[i] substringToIndex:range.location];
            }else{
                url = arrimages[i];
            }
            
            
            photo.url = [NSURL URLWithString:url]; // 图片路径
           photo.srcImageView = viewImage; // 来源于哪个UIImageView
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
//        browser.currentPhotoIndex = 0; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        [browser show];
}
#pragma 实现share方法，通过点击的视图的tag值判断是什么类型的分享
- (void)share:(UITapGestureRecognizer *)shareTap{
    NSString *url =[NSString stringWithFormat:@"http://m.niruoanhao.com/share/eme/%@",[NSString stringWithFormat:@"%.f",self.symptomEmeDetailBaseClass.data.emeid]];
    NSString *title = nil;
    NSString *message = @"万种疾病症状、病因介绍，对症推荐药品、医院、专家";
    switch (shareTap.view.tag) {

            switch (shareTap.view.tag) {
                case 11:{//微信
                    
                    [self weixinShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
                }
                    break;
                case 12:{//朋友圈
                    [self weixinFriendShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
                    
                }
                    break;
                case 13:{//短信
                    [self  showSMSPicker:url :title :message :nil];
                }
                    break;
                case 14:{//QQ
                    [self qqShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
                    
                }
                    break;
                case 15:{//QQ空间
                    [self qqZoneShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
                    
                }
                    break;
                case 16:{//新浪微博
                    [self sinaWeiboShare:url :title :message :[UIImage imageNamed:@"Icon@2x"]];
                    
                }
                    break;
                    
                default:
                    break;
            }
    }
    
}
-(void)Login{
    if ([[NSString stringWithFormat:@"%.f",self.symptomEmeDetailBaseClass.data.iscollection] isEqualToString:@"1"]) {
        /**
         *  已收藏
         */
        [self addOrDeleteCollectionUrlStr:COLLECTION_DELETE];
        
    }else{
        /**
         *  未收藏
         */
        [self addOrDeleteCollectionUrlStr:COLLECTION_ADDCOLLECTION];
        
    }
}

@end
